﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCDemo.Data;
using MVCDemo.Models;
using MVCDemo.ViewModel;

namespace MVCDemo.Controllers
{
    public class MessagesController : Controller
    {
        private   MVCDemoDb db = new MVCDemoDb();
        

        // GET: Messages
        public ActionResult Index()
        {
            if (Session["UserName"] == null)
            {
                return RedirectToRoute(new { controller = "Users", action = "Login" });
            }
            var username = Session["username"] == null ? "":Session["username"].ToString();

            var a = from u in db.Users
                    select u;

            if (username.Length > 0)
            {
                
                var users = db.Users.ToList();
                /*var msgs = db.Messages.OrderBy("").ToList();*/
                /*  var aa = from m in db.Messages
                             orderby m.Id descending
                             select m;*/
                var msgs = db.Messages.OrderByDescending(x => x.Id).ToList();
                
                //var msgs=aa.ToList();
                var cmgs = db.Comments.ToList();

                var msgViewModeList = new List<MessageViewModel>();

                
                foreach (var msg in msgs)
                {
                    var cmgViewModeList = new List<CommentViewModel>();

                 
                    var tmpComments = cmgs.Where(x => x.MsgId == msg.Id).ToList();

                 
                    foreach (var cmg in tmpComments)
                    {
                   
                        var fromUser = users.Where(x => x.Id == cmg.FromUserId).FirstOrDefault();
                                                                                                 
                        var m = msgs.Where(x => x.Id == cmg.MsgId).FirstOrDefault();
                       
                        var toUser = users.Where(x => x.Id == m.FromUserId).FirstOrDefault();

                        cmgViewModeList.Add(new CommentViewModel
                        {
                            FromUsername = fromUser.Username,
                            ToUsername = toUser.Username,
                            Comment = cmg.Comment
                        });
                    }

                   
                    msgViewModeList.Add(new MessageViewModel
                    {
                        Id = msg.Id,
                        Content = msg.Content,
                        CommentViewModels = cmgViewModeList
                    });
                }



                var vm = new SayViewModel
                {
                    Username = "haha",
                    MessageViewModel = msgViewModeList
                };

                return View(new SayViewModel
                {
                    Username = (string)Session["UserName"],
                    MessageViewModel = msgViewModeList
                });
            }
            else
            {
                Response.Redirect("/users/login");
                return View(new SayViewModel());
            }


           


            
        }





        [HttpPost]
        public void ClearAuth()
        {
            Session.Clear();
        }




        [HttpPost]
        public ActionResult SaySay(string content)
        {

            var obj = db.Messages.Add(new Messages
            {
                FromUserId = (int)Session["Id"],
                Content = content
            });


            if (Save() > 0)
            {
                return Json(new
                {
                    code=200,
                    content = content,
                    id = obj.Id
                });
            }
            else
            {
                return Json(new
                {
                    err = 320,
                    msg = "发表不成功哦！"
                });
            }


        }

        [HttpPost]
        public ActionResult Comment(string commentMsg, int msgId)
        {
            var e = from u in db.Messages
                     where u.Id == msgId
                     select u;

            var message = e.FirstOrDefault();


            var obj = db.Comments.Add(new Comments
            {
                FromUserId = (int)Session["Id"],
                MsgId = message.Id,
                Comment = commentMsg
            });


            if (Save() > 0)
            {
                var findUser = from u in db.Users
                             where u.Id == message.FromUserId
                             select u;

                var users = findUser.FirstOrDefault();

                return Json(new
                {
                    code=200,
                    FromUserName = (string)Session["Username"],
                    ToUserName = users.Username,
                    Comment = commentMsg,
                    msgId=msgId
                   
                });
            }
            else
            {
                return Json(new
                {
                    err = 300,
                    msg = "评论失败了哦！"
                });
            }
        }

        private  int Save()
        {
            return db.SaveChanges();
        }


        // GET: Messages/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // GET: Messages/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Messages/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,FromUserId,Content,CreatedAt,UpdatedAt,Version,Remarks")] Messages messages)
        {
            if (ModelState.IsValid)
            {
                db.Messages.Add(messages);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(messages);
        }

        // GET: Messages/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // POST: Messages/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,FromUserId,Content,CreatedAt,UpdatedAt,Version,Remarks")] Messages messages)
        {
            if (ModelState.IsValid)
            {
                db.Entry(messages).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(messages);
        }

        // GET: Messages/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // POST: Messages/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Messages messages = db.Messages.Find(id);
            db.Messages.Remove(messages);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
